<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8" />
    <title>用户管理系统</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link
            rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
    <link rel="stylesheet" href="UserPage.css" />
    <link rel="stylesheet" href="通用新页面css.css" />
</head>
<body>
<div id="app">
    <div class="container">
        <div class="sidebar">
            <a href="mainpage.html" class="sidebar-item">首页</a>
            <a href="dish-management.html" class="sidebar-item">菜品管理</a>
            <a href="order-management.html" class="sidebar-item">订单管理</a>
            <a href="marketing-statistics.html" class="sidebar-item">营销统计</a>
            <a href="UserPage.html" class="sidebar-item active">用户管理</a>
        </div>
        <div class="content">
            <div class="header">
                <h1>用户管理</h1>
            </div>

            <!-- 搜索区域 -->
            <div class="search-area">
                <input
                        type="text"
                        v-model="searchName"
                        placeholder="请输入用户昵称"
                />
                <input
                        type="text"
                        v-model="searchPhone"
                        placeholder="请输入手机号"
                />
                <select v-model="searchRole">
                    <option value="">全部角色</option>
                    <option value="0">超级管理员</option>
                    <option value="1">管理员</option>
                    <option value="2">普通用户</option>
                </select>
                <select v-model="searchStatus">
                    <option value="">全部状态</option>
                    <option value="1">有效</option>
                    <option value="0">无效</option>
                </select>
                <button @click="search">查询</button>
                <button class="reset" @click="reset">重置</button>
                <button class="add" @click="showAddForm">新增用户</button>
            </div>

            <!-- 用户表格 -->
            <table>
                <thead>
                <tr>
                    <th>ID</th>
                    <th>账号</th>
                    <th>昵称</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>电话</th>
                    <th>角色</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="user in users" :key="user.id">
                    <td>{{ user.id }}</td>
                    <td>{{ user.username }}</td>
                    <td>{{ user.nickname }}</td>
                    <td>{{ user.age }}</td>
                    <td>{{ user.sex === 1 ? '男' : (user.sex === 2 ? '女' : '未知') }}</td>
                    <td>{{ user.phone }}</td>
                    <td>
                                <span class="role-badge">
                                    {{ getRoleName(user.roleId) }}
                                </span>
                    </td>
                    <td>
                                <span class="status-badge" :class="user.status === 1 ? 'status-valid' : 'status-invalid'">
                                    {{ user.status === 1 ? '有效' : '无效' }}
                                </span>
                    </td>
                    <td class="operation">
                        <button class="edit" @click="editUser(user)">编辑</button>
                        <button class="delete" @click="deleteUser(user.id)">删除</button>
                    </td>
                </tr>
                <tr v-if="users.length === 0">
                    <td colspan="9" style="text-align: center; padding: 20px;">
                        暂无用户数据
                    </td>
                </tr>
                </tbody>
            </table>

            <!-- 分页控件 -->
            <div class="pagination">
                <select v-model="pageSize" @change="search">
                    <option value="5">5条/页</option>
                    <option value="10">10条/页</option>
                    <option value="15">15条/页</option>
                </select>
                <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
                <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
                <button @click="nextPage" :disabled="currentPage >= totalPages">下一页</button>
                前往
                <input type="number" v-model.number="jumpPage" min="1" :max="totalPages" />
                页
                <button @click="goToPage">跳转</button>
            </div>

            <!-- 用户表单弹窗 -->
            <div class="form-overlay" :style="{ display: showForm ? 'block' : 'none' }" @click="closeForm"></div>
            <div class="form-popup" :style="{ display: showForm ? 'block' : 'none' }">
                <div class="form-header">
                    <h2>{{ isEditing ? '编辑用户' : '新增用户' }}</h2>
                    <button class="form-close" @click="closeForm">&times;</button>
                </div>
                <div class="form-content">
                    <div class="form-group">
                        <label class="form-label">账号</label>
                        <input type="text"
                               class="form-input"
                               v-model="currentUser.username"
                               required
                               placeholder="请输入账户"
                        >
                    </div>
                    <div class="form-group">
                        <label class="form-label">昵称</label>
                        <input
                                type="text"
                                class="form-input"
                                v-model="currentUser.nickname" required
                                placeholder="请输入昵称"
                        >
                    </div>
                    <div class="form-group">
                        <label class="form-label">密码</label>
                        <input
                                type="password"
                                class="form-input"
                                placeholder="请输入密码"
                                v-model="currentUser.password"
                                :placeholder="isEditing ? '留空则不修改密码' : ''"
                                :required="!isEditing"
                        >
                    </div>
                    <div class="form-group">
                        <label class="form-label">年龄</label>
                        <input type="number" class="form-input" v-model="currentUser.age" min="0">
                    </div>
                    <div class="form-group">
                        <label class="form-label">性别</label>
                        <select class="form-input" v-model="currentUser.sex">
                            <option value="1">男</option>
                            <option value="2">女</option>
                            <option value="0">未知</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">电话</label>
                        <input
                                type="tel"
                                class="form-input"
                                v-model="currentUser.phone"
                                @input="handlePhoneInput"
                                placeholder="请输入11位手机号码"
                                maxlength="11"
                                required
                        >
                        <span class="error-message" v-if="phoneError">{{ phoneError }}</span>
                    </div>
                    <div class="form-group">
                        <label class="form-label">角色</label>
                        <select class="form-input" v-model="currentUser.roleId">
                            <option value="0">超级管理员</option>
                            <option value="1">管理员</option>
                            <option value="2">普通用户</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">状态</label>
                        <select class="form-input" v-model="currentUser.status">
                            <option value="1">有效</option>
                            <option value="0">无效</option>
                        </select>
                    </div>
                    <div class="form-actions">
                        <button class="btn btn-cancel" @click="closeForm">取消</button>
                        <button class="btn btn-primary" @click="saveUser">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    const { createApp, ref, reactive, onMounted } = Vue;

    createApp({
        setup() {
            // 用户列表数据
            const users = ref([]);

            // 搜索相关数据
            const searchName = ref("");
            const searchPhone = ref("");
            const searchRole = ref("");
            const searchStatus = ref("");
            // 电话验证相关数据
            const phoneError = ref('');

            // 分页相关数据
            const currentPage = ref(1);
            const pageSize = ref(5);
            const totalPages = ref(0);
            const totalUsers = ref(0);
            const jumpPage = ref(1);

            // 表单相关数据
            const showForm = ref(false);
            const isEditing = ref(false);
            const currentUser = reactive({
                id: null,
                username: "",
                nickname: "",
                password: "",
                age: null,
                sex: 1,
                phone: "",
                roleId: 0,
                status: 1
            });

            // 获取角色名称
            const getRoleName = (roleId) => {
                const roles = {
                    0: "超级管理员",
                    1: "管理员",
                    2: "普通用户"
                };
                return roles[roleId] || "未知角色";
            };

            // 验证电话格式
            const validatePhone = (phone) => {
                // 电话为必填项，不能为空
                if (!phone) {
                    return false;
                }
                const regex = /^[0-9]{11}$/;
                return regex.test(phone);
            };
            // 电话输入处理
            const handlePhoneInput = (event) => {
                const input = event.target.value;
                // 只允许数字输入
                const numbersOnly = input.replace(/\D/g, '');
                currentUser.phone = numbersOnly.slice(0, 11); // 限制最多11位数字

                // 实时验证
                if (!validatePhone(numbersOnly)) {
                    phoneError.value = '电话号码必须是11位数字';
                } else {
                    phoneError.value = '';
                }
            };

            // 加载用户数据
            const loadUsers = async () => {
                try {
                    // 构建查询参数
                    const params = {
                        pageNum: currentPage.value,
                        pageSize: pageSize.value,
                        user: {
                            nickname: searchName.value,
                            phone: searchPhone.value,
                            roleId: searchRole.value ? parseInt(searchRole.value) : null,
                            status: searchStatus.value ? parseInt(searchStatus.value) : null
                        }
                    };
                    console.log('小明的身份:'+ params.user.roleId)
                    // 发送请求到后端API
                    const response = await axios.post("/user/listPage", params);
                    if (response.data && response.data.code === 200) {

                        users.value = response.data.data;
                        totalUsers.value = response.data.total;
                        totalPages.value = Math.ceil(totalUsers.value / pageSize.value);
                        console.log(users.value)
                    } else {
                        alert("加载用户数据失败: " + (response.data.msg || "未知错误"));
                    }
                } catch (error) {
                    console.error("加载用户数据失败:", error);
                    alert("加载用户数据失败，请检查网络连接或后端服务");
                }
            };

            // 搜索用户
            const search = () => {
                currentPage.value = 1;
                loadUsers();
            };

            // 重置搜索条件
            const reset = () => {
                searchName.value = "";
                searchPhone.value = "";
                searchRole.value = "";
                searchStatus.value = "";
                search();
            };

            // 显示新增用户表单
            const showAddForm = () => {
                // 重置当前用户数据
                Object.assign(currentUser, {
                    id: null,
                    username: "",
                    nickname: "",
                    password: "",
                    age: null,
                    sex: 1,
                    phone: "",
                    roleId: 2,
                    status: 1
                });
                isEditing.value = false;
                showForm.value = true;
            };

            // 编辑用户
            const editUser = (user) => {
                Object.assign(currentUser, {...user});
                isEditing.value = true;
                showForm.value = true;
            };

            // 保存用户（新增或更新）
            const saveUser = async () => {
                try {
                    // 基本验证
                    if (!currentUser.username || !currentUser.nickname || (!isEditing.value && !currentUser.password)) {
                        alert("请填写必填字段");
                        return;
                    }

                    // 电话验证 - 电话现在是必填项
                    if (!validatePhone(currentUser.phone)) {
                        phoneError.value = '电话号码是必填项且必须是11位数字';
                        return;
                    }

                    let result;
                    if (isEditing.value) {
                        // 更新用户
                        result = await axios.post("/user/mod", currentUser);
                    } else {
                        // 新增用户
                        result = await axios.post("/user/save", currentUser);
                    }

                    if (result.data) {
                        alert("保存成功");
                        closeForm();
                        loadUsers();
                    } else {
                        alert("保存失败");
                    }
                } catch (error) {
                    console.error("保存用户失败:", error);
                    alert("保存用户失败，请检查网络连接或后端服务");
                }
            };

            // 删除用户
            const deleteUser = async (id) => {
                if (!confirm("确定要删除这个用户吗？")) {
                    return;
                }

                try {
                    const result = await axios.get(`/user/delete?id=${id}`);
                    if (result.data) {
                        alert("删除成功");
                        loadUsers();
                    } else {
                        alert("删除失败");
                    }
                } catch (error) {
                    console.error("删除用户失败:", error);
                    alert("删除用户失败，请检查网络连接或后端服务");
                }
            };

            // 关闭表单
            const closeForm = () => {
                showForm.value = false;
            };

            // 分页导航
            const prevPage = () => {
                if (currentPage.value > 1) {
                    currentPage.value--;
                    loadUsers();
                }
            };

            const nextPage = () => {
                if (currentPage.value < totalPages.value) {
                    currentPage.value++;
                    loadUsers();
                }
            };

            const goToPage = () => {
                if (jumpPage.value >= 1 && jumpPage.value <= totalPages.value) {
                    currentPage.value = jumpPage.value;
                    loadUsers();
                } else {
                    alert(`请输入有效的页码（1-${totalPages.value}）`);
                }
            };

            // 初始化加载数据
            onMounted(() => {
                loadUsers();
            });

            return {
                users,
                searchName,
                searchPhone,
                searchRole,
                searchStatus,
                phoneError,
                currentPage,
                pageSize,
                totalPages,
                jumpPage,
                showForm,
                isEditing,
                currentUser,
                getRoleName,
                search,
                reset,
                showAddForm,
                editUser,
                saveUser,
                deleteUser,
                closeForm,
                prevPage,
                nextPage,
                goToPage,
                handlePhoneInput
            };
        }
    }).mount("#app");
</script>
</html>
